package com.ibuonline.search.solr.extend;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.solr.schema.XscorerFactory;

import com.ibuonline.search.solr.score.ScoreRule;

@SuppressWarnings({ "rawtypes", "unchecked" })
public class ScoreHandler implements DocumentHander {
	private List<ScoreRule> scoreRules;

	@Override
	public boolean add(SolrIndexContext context) {
		final XscorerFactory xFactory = context.getRequest().getCore()
				.getSchema().getXscorerFactory();
		Map<String, Object> model = context.getModel();
		Map<String, Object> otherData = getOtherData(model);
		Map<String, Object> env = new HashMap<String, Object>();
		env.putAll(model);
		if (otherData != null) {
			env.putAll(otherData);
		}
		float score = xFactory.getOuterExpression().eval(env);
		model.put("score", score);
		return true;
	}

	protected Map<String, Object> getOtherData(Map<String, Object> model) {
		return null;
	}

	@Override
	public boolean delete(Object id) {
		return true;
	}

	protected void executeScoreRule(Map<String, Object> scoreData) {
		for (ScoreRule rule : scoreRules) {
			rule.apply(scoreData);
		}
	}

	/**
	 * @param scoreRules
	 *            the scoreRules to set
	 */
	public void setScoreRules(List<ScoreRule> scoreRules) {
		this.scoreRules = scoreRules;
	}
}
